//package com.ketangpai.admin.controller;
//
//import com.ketangpai.admin.common.Result;
//import com.ketangpai.admin.entity.StuWork;
//import com.ketangpai.admin.entity.dto.StuWorkDTO;
//import com.ketangpai.admin.service.StuWorkService;
//import com.ketangpai.admin.utils.JsonResult;
//import io.github.classgraph.Resource;
//import io.swagger.annotations.ApiOperation;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.FileSystemResource;
//import org.springframework.core.io.InputStreamResource;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.InputStream;
//import java.net.URL;
//import java.net.URLEncoder;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.List;
//import java.util.Map;
//
//@RestController
//@RequestMapping("/api/work/stuwork")
//public class StuWorkController {
//
//    @Autowired
//    private StuWorkService stuWorkService;
//
//    @GetMapping("/list")
//    public Result<Map<String, Object>> getStudentWorks(
//            @RequestParam Integer workId,
//            @RequestParam(required = false) Integer status,
//            @RequestParam(required = false) String studentName,
//            @RequestParam(defaultValue = "1") Integer page,
//            @RequestParam(defaultValue = "10") Integer pageSize) {
//        try {
//            Map<String, Object> result = stuWorkService.getStudentWorks(workId, status, studentName, page, pageSize);
//            return Result.success(result);
//        } catch (Exception e) {
//            return Result.error("获取学生作业列表失败：" + e.getMessage());
//        }
//    }
//    /**
//     * 通过主键查询单条数据
//     */
//    @ApiOperation("根据id查询")
//    @GetMapping("/selectById/{id}")
//    public JsonResult<?> selectById(@PathVariable Integer id) {
//        StuWork stuWork = stuWorkService.queryById(id);
//        return JsonResult.success(stuWork);
//    }
//    @PostMapping("/grade")
//    public Result<Boolean> submitWorkGrade(
//            @RequestParam Integer id,
//            @RequestParam String score,
//            @RequestParam(required = false) String message) {
//        try {
//            boolean success = stuWorkService.submitWorkGrade(id, score, message);
//            return success ? Result.success(true) : Result.error("提交评分失败");
//        } catch (Exception e) {
//            return Result.error("提交评分失败：" + e.getMessage());
//        }
//    }
//
//    @PostMapping("/expedite/{id}")
//    public Result<Boolean> expediteSubmission(@PathVariable Integer id) {
//        try {
//            boolean success = stuWorkService.expediteSubmission(id);
//            return success ? Result.success(true) : Result.error("催交失败");
//        } catch (Exception e) {
//            return Result.error("催交失败：" + e.getMessage());
//        }
//    }
//
//    @PostMapping("/status")
//    public Result<Boolean> updateWorkStatus(
//            @RequestParam Integer id,
//            @RequestParam Integer status) {
//        try {
//            boolean success = stuWorkService.updateWorkStatus(id, status);
//            return success ? Result.success(true) : Result.error("更新状态失败");
//        } catch (Exception e) {
//            return Result.error("更新状态失败：" + e.getMessage());
//        }
//    }
//    @ApiOperation("根据用户、课/stuWork/update程id查询作业")
//    @GetMapping("/selectByUCid/{cid}/{uid}")
//    public JsonResult<?> queryByUCid(@PathVariable Integer cid, @PathVariable Integer uid) {
//        List<StuWorkDTO> stuWork = stuWorkService.queryByUCid(cid, uid);
//        return JsonResult.success(stuWork);
//    }
//    // StuWorkController.java
//    @GetMapping("/detail/{id}")
//    public Result<StuWork> getStudentWorkDetail(@PathVariable Integer id) {
//        try {
//            StuWork stuWork = stuWorkService.getStudentWorkDetail(id);
//            return Result.success(stuWork);
//        } catch (Exception e) {
//            return Result.error("获取作业详情失败：" + e.getMessage());
//        }
//    }
//    @GetMapping("/download/{id}")
//    public ResponseEntity<?> downloadWork(@PathVariable Integer id) {
//        try {
//            StuWork stuWork = stuWorkService.getStudentWorkDetail(id);
//            if (stuWork == null || stuWork.getFilename() == null) {
//                return ResponseEntity.badRequest().body("文件不存在");
//            }
//
//            // 从 OSS URL 中获取文件名
//            String fileName = stuWork.getFilename().substring(stuWork.getFilename().lastIndexOf("/") + 1);
//
//            // 从 OSS 获取文件
//            URL url = new URL(stuWork.getFilename());
//            InputStream inputStream = url.openStream();
//
//            // 设置响应头
//            return ResponseEntity.ok()
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"")
//                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
//                    .body(new InputStreamResource(inputStream));
//
//        } catch (Exception e) {
//            return ResponseEntity.badRequest().body("文件下载失败: " + e.getMessage());
//        }
//    }
//
//    @PostMapping("/update")
//    public JsonResult update( StuWork stuWork){
//        // 显式处理 checkTime 为 null 的情况
//        if (stuWork.getCheckTime() == null) {
//            stuWork.setCheckTime(null); // 确保 checkTime 为 null
//        }
//        boolean result = stuWorkService.update(stuWork);
//        if (result) {
//            return JsonResult.success("编辑成功");
//        }
//        return JsonResult.error("编辑失败");
//    }
//
//}
package com.ketangpai.admin.controller;

import com.ketangpai.admin.common.Result;
import com.ketangpai.admin.entity.StuWork;
import com.ketangpai.admin.entity.dto.StuWorkDTO;
import com.ketangpai.admin.service.StuWorkService;
import com.ketangpai.admin.utils.JsonResult;
import io.github.classgraph.Resource;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/work/stuwork")
public class StuWorkController {

    @Autowired
    private StuWorkService stuWorkService;

    @GetMapping("/list")
    public Result<Map<String, Object>> getStudentWorks(
            @RequestParam Integer workId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String studentName,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = stuWorkService.getStudentWorks(workId, status, studentName, page, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取学生作业列表失败：" + e.getMessage());
        }
    }
    /**
     * 通过主键查询单条数据
     */
    @ApiOperation("根据id查询")
    @GetMapping("/selectById/{id}")
    public JsonResult<?> selectById(@PathVariable Integer id) {
        StuWork stuWork = stuWorkService.queryById(id);
        return JsonResult.success(stuWork);
    }
    @PostMapping("/grade")
    public Result<Boolean> submitWorkGrade(
            @RequestParam Integer id,
            @RequestParam String score,
            @RequestParam(required = false) String message) {
        try {
            boolean success = stuWorkService.submitWorkGrade(id, score, message);
            return success ? Result.success(true) : Result.error("提交评分失败");
        } catch (Exception e) {
            return Result.error("提交评分失败：" + e.getMessage());
        }
    }

    @PostMapping("/expedite/{id}")
    public Result<Boolean> expediteSubmission(@PathVariable Integer id) {
        try {
            boolean success = stuWorkService.expediteSubmission(id);
            return success ? Result.success(true) : Result.error("催交失败");
        } catch (Exception e) {
            return Result.error("催交失败：" + e.getMessage());
        }
    }

    @PostMapping("/status")
    public Result<Boolean> updateWorkStatus(
            @RequestParam Integer id,
            @RequestParam Integer status) {
        try {
            boolean success = stuWorkService.updateWorkStatus(id, status);
            return success ? Result.success(true) : Result.error("更新状态失败");
        } catch (Exception e) {
            return Result.error("更新状态失败：" + e.getMessage());
        }
    }
    @ApiOperation("根据用户、课/stuWork/update程id查询作业")
    @GetMapping("/selectByUCid/{cid}/{uid}")
    public JsonResult<?> queryByUCid(@PathVariable Integer cid, @PathVariable Integer uid) {
        List<StuWorkDTO> stuWork = stuWorkService.queryByUCid(cid, uid);
        return JsonResult.success(stuWork);
    }
    // StuWorkController.java
    @GetMapping("/detail/{id}")
    public Result<StuWork> getStudentWorkDetail(@PathVariable Integer id) {
        try {
            StuWork stuWork = stuWorkService.getStudentWorkDetail(id);
            return Result.success(stuWork);
        } catch (Exception e) {
            return Result.error("获取作业详情失败：" + e.getMessage());
        }
    }
    @GetMapping("/download/{id}")
    public ResponseEntity<?> downloadWork(@PathVariable Integer id) {
        try {
            StuWork stuWork = stuWorkService.getStudentWorkDetail(id);
            if (stuWork == null || stuWork.getFilename() == null) {
                return ResponseEntity.badRequest().body("文件不存在");
            }

            // 从 OSS URL 中获取文件名
            String fileName = stuWork.getFilename().substring(stuWork.getFilename().lastIndexOf("/") + 1);

            // 从 OSS 获取文件
            URL url = new URL(stuWork.getFilename());
            InputStream inputStream = url.openStream();

            // 设置响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .body(new InputStreamResource(inputStream));

        } catch (Exception e) {
            return ResponseEntity.badRequest().body("文件下载失败: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public JsonResult update( StuWork stuWork){
        boolean result = stuWorkService.update(stuWork);
        if (result) {
            return JsonResult.success("编辑成功");
        }
        return JsonResult.error("编辑失败");
    }

}
